package zy.wq.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.password.StandardPasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import zy.wq.security.service.SystemUserService;
import zy.wq.security.support.SystemUserAuthenticationProvider;





/**
 * @author lenovo
 *
 */
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired private HttpOutputMessageWriter httpOutputMessageWriter;
	
	@Autowired private AuthenticationEntryPoint restAuthenticationEntryPoint;


	@Override
	protected void configure(HttpSecurity http) throws Exception {
		// TODO Auto-generated method stub
		RestAuthenticationFilter restAuthenticationFilter = new RestAuthenticationFilter();
		restAuthenticationFilter.setHttpOutputMessageWriter(httpOutputMessageWriter);
		restAuthenticationFilter.setAuthenticationManager(this.authenticationManager());
		restAuthenticationFilter.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/authenticate", null));
		restAuthenticationFilter.setPostOnly(false);
		
		restAuthenticationFilter.afterPropertiesSet();
		http.csrf().disable().authorizeRequests()
			.antMatchers("/**").permitAll()
			.and()
			.addFilterAt(restAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
			.exceptionHandling().authenticationEntryPoint(restAuthenticationEntryPoint);
	}

	
	@Bean HttpOutputMessageWriter HttpOutputMessageWriter(HttpMessageConverters messageConverters) {
		HttpOutputMessageWriter w = new HttpOutputMessageWriter();
		w.setMessageConverters(messageConverters);
		return w;
	}
	
	@Bean
	public AuthenticationEntryPoint restAuthenticationEntryPoint(HttpMessageConverters messageConverters) {
		RestAuthenticationEntryPoint e = new RestAuthenticationEntryPoint();
		e.setOutputMessageWriter(httpOutputMessageWriter);
		return e;
	}
	

	@Bean
	public PasswordEncoder passwordEncoder() {
		return new StandardPasswordEncoder();
	}
	
	@Bean
	SystemUserAuthenticationProvider userAuthenticationProvider(SystemUserService userService,PasswordEncoder passwordEncoder) {
		SystemUserAuthenticationProvider p = new SystemUserAuthenticationProvider();
		p.setPasswordEncoder(passwordEncoder);
		p.setSystemUserService(userService);
		return p;
	}
	
	
	
}
